package com.huidian.gitbatchprocessing.git.util;

import com.alibaba.fastjson.JSON;
import com.huidian.gitbatchprocessing.config.CredentialsConfig;
import com.huidian.gitbatchprocessing.ui.dialog.UserPasswordInputDialog;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;

/**
 * 初始化工具
 *
 * @author zxb
 * @date 2021/6/21
 */
public class CredentialsUtil {
    /**
     * 存储本地配置的唯一键
     */
    public static final String CREDENTIALS_CONFIG_KEY = "com.huidian.git-batch_credentialsConfigKey";

    /**
     * 从本地存储加载用户信息
     *
     * @param project
     * @return
     */
    public static CredentialsConfig getCredentialsConfigFromLocal(Project project) {
        PropertiesComponent propertiesComponent = getPropertiesComponent(project);
        String value = propertiesComponent.getValue(CREDENTIALS_CONFIG_KEY);
        return StringUtil.isEmpty(value) ? showUserPasswordInputDialog(project) : JSON.parseObject(value, CredentialsConfig.class);
    }

    /**
     * 存储用户信息到本地
     *
     * @param project
     * @return
     */
    public static void setCredentialsConfigToLocal(Project project, CredentialsConfig credentialsConfig) {
        PropertiesComponent propertiesComponent = getPropertiesComponent(project);
        propertiesComponent.unsetValue(CREDENTIALS_CONFIG_KEY);
        propertiesComponent.setValue(CREDENTIALS_CONFIG_KEY, JSON.toJSONString(credentialsConfig));
    }

    /**
     * 输入用户名、密码
     *
     * @return
     */
    public static CredentialsConfig showUserPasswordInputDialog(Project project) {
        UserPasswordInputDialog userPasswordInputDialog = new UserPasswordInputDialog(null, ApplicationUtil.getFrameInstance().getFrame());
        userPasswordInputDialog.setVisible(Boolean.TRUE);
        CredentialsConfig credentialsConfig = userPasswordInputDialog.getCredentialsConfig();
        if (userPasswordInputDialog.endurance()) {
            setCredentialsConfigToLocal(project, credentialsConfig);
        }
        return credentialsConfig;
    }


    private static PropertiesComponent getPropertiesComponent(Project project) {
        PropertiesComponent instance;
        if (project == null) {
            instance = PropertiesComponent.getInstance();
        } else {
            instance = PropertiesComponent.getInstance(project);
        }
        return instance;
    }
}
